<template>
  <div class>
    <input type="file" @change="doUpload($event)">
    <br>
    <el-upload
      ref="upload"
      class="upload-demo"
      :on-success="handleSucc"
      :action="hostSetting.host+'/admin/xy/upload/uploadImg'"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
    <img :src="imgUrl" alt>
  </div>
</template>

<script>
import axios from 'axios'
import hostSetting from '@/api/host-setting'
export default {
  name: 'DemoMaterial',
  components: {},
  data() {
    return {
      imgUrl: '',
      fileList: [],
      hostSetting
    }
  },
  computed: {},
  created() {},
  mounted() {},
  methods: {
    // 强调: 一般来说上传分两种形式; 1 . 直接把input直接放到form中 通过form的action直接提交 (古老)
    // 2. ajax异步提交   把input的file文件包装为formData对象 通过ajax提交
    doUpload(e) {
      // 获取input dom元素
      var target = e.target
      // 上传可以多选
      var file = target.files[0]
      // file文件如何直接传递后台  后台可以直接接收formData数据
      var fd = new FormData()
      // 同过 append 方法添加到后台需要的key中  一般后台对于单个文件提交 默认都是 file
      fd.append('file', file) // key=v&key=v....

      // ajax提交
      const api = hostSetting.host + '/admin/xy/upload/uploadImg'
      axios.post(api, fd).then(res => {
        console.log('res,', res)
        // media/20200415142439.jpg
        this.imgUrl = hostSetting.host + '/' + res.data.url
      })
    },
    // 处理成功的回调
    handleSucc(response, file, fileList) {
      // console.log(response);
    //   if(response.url){

      //   }else{
      //       //失败...
      //   }
      this.imgUrl = hostSetting.host + '/' + response.url
      this.$refs.upload.clearFiles()
    }
  }
}
</script>

<style scoped lang="scss">
</style>
